﻿// LdrbInstruction.cs
// Contains a class for a ldrb instruction


using System;

namespace armsim
{

    /// <summary>
    /// Class for an Ldrb Arm Instruction
    /// </summary>
    public class LdrbInstruction : LoadStoreInstruction
    {

        /// <summary>
        /// Initializes a new LdrbInstruction
        /// </summary>
        /// <param name="instruction">itialized from this</param>
        public LdrbInstruction(uint instruction)
            : base(instruction)
        {
        }

        /// <summary>
        /// Executes the instruction
        /// </summary>
        /// <param name="cpu">Executes from the cpu and stores the results in the cpu</param>
        public override void Execute(VirtualCPU cpu)
        {

            var rn = cpu.Registers.ReadRegistersDuringExecute(VirtualMemory.MapRegNoToRegMem(this.Rn));
            var offset = this.Offset.ComputeOffset(cpu);
            var memory = this.U == 1u ? cpu.RAM.ReadByte(rn + offset) : cpu.RAM.ReadByte(rn - offset);

            cpu.Registers.WriteWord(VirtualMemory.MapRegNoToRegMem(this.Rd), 0);
            cpu.Registers.WriteByte(VirtualMemory.MapRegNoToRegMem(this.Rd), memory);

        }

        /// <summary>
        /// Converts the instruction to assembly code
        /// </summary>
        /// <param name="cpu">grabs info from here</param>
        /// <returns>the assembly code</returns>
        public override string ToAssembly(VirtualCPU cpu)
        {
            return String.Format("LDRB {0}", base.ToAssembly(cpu));
        }

    }
}
